package com.wxzl.community.common.http

import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.parse.AbstractParser
import rxhttp.wrapper.utils.convert
import java.io.IOException
import java.lang.reflect.Type

@Parser(name = "Response")
open class ResponseParser<T> : AbstractParser<T> {

    //以下两个构造方法是必须的
    protected constructor() : super()
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: okhttp3.Response): T {

        val type: Type = ParameterizedTypeImpl[Response::class.java, mType] //获取泛型类型
        val data: Response<T> = response.convert(type)
        if (data.code  == 200 || data.code == 10000) { //code不等于200，说明数据不正确，抛出异常
            if (data.data==null ){
                throw DataNullException(data.code, data.msg  )
            }else {
                return data.data!!
            }

        }else{
            throw ApiException(data.code, data.msg  )

        }



    }
}
